package c.w.mapTools;

import android.app.Application;
import android.app.ProgressDialog;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Vibrator;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.BDNotifyListener;
import com.baidu.location.LocationClient;
import com.baidu.mapapi.map.MapController;

public class LocationProxy extends Application {

	public LocationClient locationClient = null;
	public NotifyListener notifyLis = null;
	public Vibrator vibrator = null;
	public MapController mapController = null;
	private ProgressDialog dia = null;
//	private OverlayFactory overlayFactory = null;
//	private ConnectionManager connManager = null;
	private SoundPool soundPool = null;
	private int superpositionAlert;//定义一个整型用load（）；来设置suondID
	private static int SUP_NUM = 0;
	private static String SUP_CAR_ID = "0";
	
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		
		locationClient = new LocationClient(this);
		
		locationClient.registerLocationListener(new MyLocationListenner());
		
		notifyLis = new NotifyListener();
		
//		connManager = new ConnectionManager();
		
		//与经度30.580145, 纬度103.98975相差50米时调用
//		notifyLis.SetNotifyLocation(30.580145, 103.98975, 3000, "gps");
		
//		locationClient.registerNotify(notifyLis);
		
		//声音文件的处理
		soundPool = new SoundPool(3, AudioManager.STREAM_SYSTEM, 5);//第一个参数为同时播放数据流的最大个数，第二数据流类型，第三为声音质量
//		superpositionAlert = soundPool.load(this, R.raw.superposition, 1);//把你的声音素材放到res/raw里，第2个参数即为资源文件，第3个为音乐的优先级
		
		super.onCreate();
	}
	
	
	/*
	 * 获取经纬度成功时调用该函数实现地图中心位置的显示
	 * */
	private void whenSearchLngLatSuccess() {
//		if (SystemConstants.LATITUDE != 0.0) {
		if (true) {
		
//			List<CarInformation> resultList = new ArrayList<CarInformation>();
//			double lng = SystemConstants.LONGITUDE;
//			double lat = SystemConstants.LATITUDE;
			//需要有用户选择收索范围后转换为经纬度
			double seachScopeX = 0.005;
			double seachScopeY = 0.005;
			
			//连接服务器的操作
			String resultData = null; //connManager.callBaseService(SystemConstants.OURCITY, lng, lat, seachScopeX, seachScopeY, null);
			
			if (resultData == null || "".equals(resultData)) {
//				this.dia = MainActivity.dia;
    			dia.dismiss();
    			dia.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    			dia.setIndeterminate(false);
    			dia.setCancelable(true);
    			dia.setMessage("服务器连接失败");
    			dia.show();
    			//自动处理该类问题,回调callServer函数,超过5次提示系统繁忙,超过10次提示用户反馈并不再连接服务器
			} else {
				
//				if ("0".equals(SystemConstants.CONNECTIONUPDATE)) {
//					SystemConstants.CONNECTIONUPDATE = "1";
//				}
				
//				GeoPoint point = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));//GeoPoint(int latitudeE6, int longitudeE6)
//				mapController.setCenter(point);
//				Drawable marker = this.getResources().getDrawable(R.drawable.man);
//				overlayFactory = new OverlayFactory(marker, MainActivity.mainContext, MainActivity.mapView);
//				overlayFactory.createOverlayItem(SystemConstants.LONGITUDE, SystemConstants.LATITUDE);
//				overlayFactory.addOverlay(lat, lng);//所有的都是lat在前
//				MainActivity.mapView.getOverlays().clear();
				
//				MainActivity.mapView.getOverlays().add(overlayFactory);

//				MainActivity.mapView.refresh();
				
//				marker = this.getResources().getDrawable(R.drawable.car);
//				overlayFactory = new OverlayFactory(marker, MainActivity.mainContext, MainActivity.mapView);
				
//				resultList = SystemVialdata.getCras(SystemVialdata.setOurId(SystemVialdata.dataReplay(resultData)));
//				for (int i = 0; i < resultList.size(); i++) {
//	    			CarInformation car = resultList.get(i);
					//需要判定是否在固定范围内,如果在强制退出
//					if(compareIsScope(lng, lat, car.getLongitude(), car.getLatitude())) {
//						//向服务器发送断开信息
//						//提示并开始计时,超时强制退出程序
//					}
	    			
//	    			double carLat = car.getLatitude();
//	    			double carLng = car.getLongitude();
//	    			GeoPoint comparePoint = new GeoPoint((int) (carLat * 1E6), (int) (carLng * 1E6));
	    			
//	    			if (DistanceUtil.getDistance(point, comparePoint) <= SystemConstants.SHOULD_EXIT_SCOPE) {
//	    				if ("0".equals(SUP_CAR_ID) || SUP_CAR_ID.equals(car.getId())) {
//		    				//开始启用重合时的方法---计时退出
//		    				whenMarkerSuperposition();
//	    				} else {
//	    					SUP_NUM = 0;
//	    				}
//	    				SUP_CAR_ID = car.getId();
//	    			}
	    			
//					overlayFactory.addOverlay(carLat, carLng);
//	    		}
				
//				MainActivity.mapView.getOverlays().add(overlayFactory);

//				MainActivity.mapView.refresh();
				//与经度30.580145, 纬度103.98975相差50米时调用
//				notifyLis.SetNotifyLocation(lat, lng, 20, "gps");
				
				locationClient.registerNotify(notifyLis);
				
//				if (SystemConstants.INVITE_RUN) {
	    			
//					InviteService iService = new InviteService();
	    			
//	    			String successMessage = iService.inviteSuccessOrNot(resultData);
//	    			
//	    			System.out.println("邀请信息是-----" + successMessage);
	    			
//	    			if (successMessage.equals(SystemConstants.INVITE_SUCCESS)) {
//	    				/*---------------------------------4、显示效果为UI设计中的“邀请确定信息”,显示内容为邀请成功-----------------------------*/
//	    			} else if (successMessage.equals(SystemConstants.INVITE_FAIL)) {
//	    				/*---------------------------------5、显示效果为UI设计中的“邀请确定信息”,显示内容为邀请失败-----------------------------*/
//	    			} else if (successMessage.equals(SystemConstants.INVITE_WAITE)) {
//	    				
//	    			}
	    			
//	    			this.dia = MainActivity.dia;
	    			dia.dismiss();
	    			dia.setProgressStyle(ProgressDialog.STYLE_SPINNER);
	    			dia.setIndeterminate(false);
	    			dia.setCancelable(true);
//	    			dia.setMessage("邀请信息是-----" + successMessage);
	    			dia.show();
//	    		}
				
				/*-------------------------------------2、显示效果为UI设计中的“服务器响应成功”---------------------------------------*/
			}
			
			/*this.dia = MainActivity.dia;
			dia.dismiss();
			dia.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			dia.setIndeterminate(false);
			dia.setCancelable(true);
			dia.setMessage("定位成功...");
			dia.show();*/
			
		}
	}
	
	/*
	 * 当标记重合的时候调用的方法,开始计时,超过30秒,退出
	 * */
	private void whenMarkerSuperposition() {
		
		SUP_NUM ++;
		
//		if (SUP_NUM == SystemConstants.SUPERPOSITION_WAITE_NUM) {
//			soundPool.play(superpositionAlert, 1, 1, 0, 0, 1);
			/*-------------------------------------6、显示效果为UI设计中的“当人打车成功时”---------------------------------------*/
//		}
		
//		this.dia = MainActivity.dia;
		dia.dismiss();
		dia.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		dia.setIndeterminate(false);
		dia.setCancelable(true);
		dia.setMessage("有坐标重合，计时30’后仍重合则等效于打车success");
		dia.show();
	}
	
	/**
	 * 监听函数，更新位置的时候，格式化成字符串
	 */
	public class MyLocationListenner implements BDLocationListener {
		@Override
		public void onReceiveLocation(BDLocation location) {
			if (location == null)
				return ;
			StringBuffer sb = new StringBuffer(256);
			sb.append("time : ");
			sb.append(location.getTime());
			sb.append("\nerror code : ");
			sb.append(location.getLocType());
			sb.append("\nlatitude : ");
			sb.append(location.getLatitude());
//			SystemConstants.LATITUDE = location.getLatitude();
			
			sb.append("\nlontitude : ");
			sb.append(location.getLongitude());
//			SystemConstants.LONGITUDE = location.getLongitude();
			
			System.out.println("获取到经度纬度是----"+location.getLatitude()+"----"+location.getLongitude());
			sb.append("\nradius : ");
			sb.append(location.getRadius());
			if (location.getLocType() == BDLocation.TypeGpsLocation){
				sb.append("\nspeed : ");
				sb.append(location.getSpeed());
				sb.append("\nsatellite : ");
				sb.append(location.getSatelliteNumber());
				//如何获得城市?
//				dia = MainActivity.dia;
				dia.dismiss();
				dia.setProgressStyle(ProgressDialog.STYLE_SPINNER);
				dia.setIndeterminate(false);
				dia.setCancelable(true);
				dia.setMessage("我所在的城市代号,只有网络部定位才能获取城市,需要进行逆编码----" +location.getSatelliteNumber());
				dia.show();
			} else if (location.getLocType() == BDLocation.TypeNetWorkLocation){
//				sb.append("\n省：");
//				sb.append(location.getProvince());
//				sb.append("\n市：");
//				sb.append(location.getCity());
//				sb.append("\n区/县：");
//				sb.append(location.getDistrict());
//				SystemConstants.OURCITY = location.getCity();
//				dia = MainActivity.dia;
				dia.dismiss();
				dia.setProgressStyle(ProgressDialog.STYLE_SPINNER);
				dia.setIndeterminate(false);
				dia.setCancelable(true);
//				dia.setMessage("我所在的城市----" +SystemConstants.OURCITY);
				dia.show();
				sb.append("\naddr : ");
				sb.append(location.getAddrStr());
			}
			sb.append("\nsdk version : ");
			sb.append(locationClient.getVersion());
			sb.append("\nisCellChangeFlag : ");
			sb.append(location.isCellChangeFlag());
			
			whenSearchLngLatSuccess();
		}
		
		public void onReceivePoi(BDLocation poiLocation) {
			if (poiLocation == null){
				return ; 
			}
			StringBuffer sb = new StringBuffer(256);
			sb.append("Poi time : ");
			sb.append(poiLocation.getTime());
			sb.append("\nerror code : "); 
			sb.append(poiLocation.getLocType());
			sb.append("\nlatitude : ");
			sb.append(poiLocation.getLatitude());
			sb.append("\nlontitude : ");
			sb.append(poiLocation.getLongitude());
			sb.append("\nradius : ");
			sb.append(poiLocation.getRadius());
			if (poiLocation.getLocType() == BDLocation.TypeNetWorkLocation){
				sb.append("\naddr : ");
				sb.append(poiLocation.getAddrStr());
			} 
			if(poiLocation.hasPoi()){
				sb.append("\nPoi:");
				sb.append(poiLocation.getPoi());
			}else{				
				sb.append("noPoi information");
			}
//			Log.v("poi message ---",sb.toString());
//			dia = MainActivity.dia;
			dia.dismiss();
			dia.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			dia.setIndeterminate(false);
			dia.setCancelable(true);
			dia.setMessage("poi 信息 --- " + sb.toString());
			dia.show();
			whenSearchLngLatSuccess();
		}
	}
	
	//在范围内的监听
	public class NotifyListener extends BDNotifyListener {
		@Override
		public void onNotify(BDLocation location, float distance) {
			// TODO Auto-generated method stub
//			super.onNotify(location, distance);
			//设置震动时长
//			vibrator.vibrate(1000);
//			dia = MainActivity.dia;
			dia.dismiss();
			dia.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			dia.setIndeterminate(false);
			dia.setCancelable(true);
			dia.setMessage("在收缩范围内--震动--");
			dia.show();
			//频率版震动
			//停0.01秒之後震動0.1秒(重覆六次)
			vibrator.vibrate(new long[]{100, 1000, 100, 1000, 100, 1000, 100, 1000, 100, 1000, 100, 1000}, -1);
			soundPool.play(superpositionAlert, 1, 1, 0, 0, 1);
		}
	}
	
}
